@extends('layouts.app')

@section('content')
<div class="container">
    <!-- 添加 CSRF token meta 标签 -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <div class="row justify-content-center">
        <div class="col-md-12">
            <!-- 返回首页按钮 -->
            <div class="mb-3">
                <a href="{{ route('home') }}" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> 返回首页
                </a>
            </div>

            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <span>微信用户列表</span>
                    </div>
                </div>

                <!-- 添加搜索表单 -->
                <div class="card-body border-bottom">
                    <form method="GET" action="{{ url()->current() }}" class="row g-3 align-items-center">
                        <div class="col-auto">
                            <input type="text" 
                                   name="search" 
                                   class="form-control" 
                                   placeholder="输入用户ID或昵称" 
                                   value="{{ request('search') }}">
                        </div>
                        <div class="col-auto">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i> 查询
                            </button>
                            @if(request('search'))
                                <a href="{{ url()->current() }}" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> 清除
                                </a>
                            @endif
                        </div>
                    </form>
                </div>

                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>OpenID</th>
                                    <th>昵称</th>
                                    <th>创建时间</th>
                                    <th>更新时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                @if($wechatUsers->isEmpty())
                                    <tr>
                                        <td colspan="5" class="text-center">未找到匹配的用户记录</td>
                                    </tr>
                                @else
                                    @foreach ($wechatUsers as $user)
                                    <tr>
                                        <td>{{ $user->id }}</td>
                                        <td>{{ $user->openid }}</td>
                                        <td>{{ $user->nickname }}</td>
                                        <td>{{ $user->created_at->format('Y-m-d H:i:s') }}</td>
                                        <td>{{ $user->updated_at->format('Y-m-d H:i:s') }}</td>
                                        <td>
                                            <button type="button" 
                                                    class="btn btn-primary btn-sm"
                                                    onclick="showBindDialog({{ $user->id }})">
                                                绑定兑换码
                                            </button>
                                        </td>
                                    </tr>
                                    @endforeach
                                @endif
                            </tbody>
                        </table>
                    </div>

                    @if($wechatUsers->hasPages())
                    <div class="mt-4">
                        {{ $wechatUsers->appends(request()->except('page'))->links('vendor.pagination.custom') }}
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- 添加绑定兑换码的模态框 -->
    <div class="modal fade" id="bindCodeModal" tabindex="-1" aria-labelledby="bindCodeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="bindCodeModalLabel">绑定兑换码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger" id="bindError" style="display: none;"></div>
                    <div class="alert alert-success" id="bindSuccess" style="display: none;"></div>
                    <form id="bindCodeForm">
                        <input type="hidden" id="userId" name="userId">
                        <div class="mb-3">
                            <label for="cardNumber" class="form-label">兑换码卡号</label>
                            <input type="text" class="form-control" id="cardNumber" name="cardNumber" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="bindCode()">确认绑定</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    window.showBindDialog = function(userId) {
        console.log('showBindDialog called with userId:', userId);
        try {
            document.getElementById('userId').value = userId;
            document.getElementById('bindError').style.display = 'none';
            document.getElementById('bindSuccess').style.display = 'none';
            document.getElementById('cardNumber').value = '';
            
            const modalElement = document.getElementById('bindCodeModal');
            console.log('Modal element:', modalElement);
            
            const modal = new bootstrap.Modal(modalElement);
            modal.show();
        } catch (error) {
            console.error('Error in showBindDialog:', error);
        }
    };

    // 添加完整的 bindCode 函数实现
    window.bindCode = function() {
        console.log('bindCode called');
        
        // 获取表单数据
        const userId = document.getElementById('userId').value;
        const cardNumber = document.getElementById('cardNumber').value;
        
        // 验证输入
        if (!cardNumber) {
            showError('请输入兑换码卡号');
            return;
        }

        // 发送绑定请求
        fetch('/admin/lottery/bind-code', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                user_id: userId,
                card_number: cardNumber
            })
        })
        .then(async response => {
            const text = await response.text();
            console.log('Raw response:', text);
            
            try {
                const data = JSON.parse(text);
                if (data.success) {
                    showSuccess(data.message || '绑定成功');
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    showError(data.message || '绑定失败');
                }
            } catch (e) {
                console.error('JSON parsing error:', e);
                showError('服务器响应格式错误');
            }
        })
        .catch(error => {
            console.error('Request error:', error);
            showError('请求失败，请稍后重试');
        });
    };

    // 添加完整的错误显示函数
    window.showError = function(message) {
        const errorDiv = document.getElementById('bindError');
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
        document.getElementById('bindSuccess').style.display = 'none';
    };

    // 添加完整的成功显示函数
    window.showSuccess = function(message) {
        const successDiv = document.getElementById('bindSuccess');
        successDiv.textContent = message;
        successDiv.style.display = 'block';
        document.getElementById('bindError').style.display = 'none';
    };
});
</script>
@endsection 